package com.example.myapplication2;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myapplication2.db.UserDao;

public class MainActivity extends AppCompatActivity {
    private EditText etAccount, etPassword;
    private CheckBox cbRememberPassword;
    private UserDao userDao;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 初始化视图和数据库
        initViews();
        userDao = new UserDao(this);
        sharedPreferences = getSharedPreferences("login_info", MODE_PRIVATE);

        // 加载保存的登录信息
        loadSavedLoginInfo();

        // 设置按钮点击事件
        setupButtonListeners();
    }

    private void initViews() {
        etAccount = findViewById(R.id.et_account);
        etPassword = findViewById(R.id.et_password);
        cbRememberPassword = findViewById(R.id.cb_remember_password);
    }

    private void loadSavedLoginInfo() {
        if (sharedPreferences.getBoolean("remember_password", false)) {
            String savedUsername = sharedPreferences.getString("username", "");
            String savedPassword = sharedPreferences.getString("password", "");
            etAccount.setText(savedUsername);
            etPassword.setText(savedPassword);
            cbRememberPassword.setChecked(true);
        }
    }

    private void setupButtonListeners() {
        // 登录按钮
        findViewById(R.id.btn_login).setOnClickListener(v -> handleLogin());

        // 注册按钮
        findViewById(R.id.btn_register).setOnClickListener(v -> handleRegister());
    }

    private void handleLogin() {
        String username = etAccount.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (validateInput(username, password)) {
            // 先验证用户名和密码
            if (userDao.validateUser(username, password)) {
                // 验证成功后获取用户ID
                long userId = userDao.getUserId(username);
                saveLoginInfo(username, password);
                
                // 保存用户ID
                SharedPreferences.Editor editor = getSharedPreferences("user_info", MODE_PRIVATE).edit();
                editor.putLong("user_id", userId);
                editor.apply();
                
                // 跳转到主页面
                Intent intent = new Intent(MainActivity.this, TodoListActivity.class);
                startActivity(intent);
                finish();
            } else {
                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void handleRegister() {
        String username = etAccount.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (validateInput(username, password)) {
            if (userDao.isUserExists(username)) {
                Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
            } else if (userDao.registerUser(username, password)) {
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean validateInput(String username, String password) {
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void saveLoginInfo(String username, String password) {
        if (cbRememberPassword.isChecked()) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("username", username);
            editor.putString("password", password);
            editor.putBoolean("remember_password", true);
            editor.apply();
        } else {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear();
            editor.apply();
        }
    }

    private void startTodoListActivity() {
        try {
            Intent intent = new Intent(this, TodoListActivity.class);
            startActivity(intent);
            finish();
        } catch (Exception e) {
            Toast.makeText(this, "启动失败，请重试", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}